// 自动绑卡脚本
// 异步函数，用于自动绑定银行卡
async function autoBindCard(cardInfo) {
    console.log(`[${new Date().toLocaleString()}] 开始执行绑卡流程...`);
    console.log(`[${new Date().toLocaleString()}] 卡信息:`, {
        ...cardInfo,
        cardNumber: cardInfo.cardNumber.replace(/\d{4}(?=\d{4})/g, "****") // 隐藏部分卡号
    });

    try {
        // 第一步：创建Stripe token
        console.log(`[${new Date().toLocaleString()}] 正在创建Stripe token...`);
        const tokenResponse = await fetch("https://api.stripe.com/v1/tokens", {
            method: "POST",
            headers: {
                "accept": "application/json",
                "content-type": "application/x-www-form-urlencoded",
                "Referer": "https://js.stripe.com/",
                "Referrer-Policy": "strict-origin-when-cross-origin"
            },
            body: new URLSearchParams({
                "guid": "547bf7ae-a577-4240-8f3b-fe57582fd27279294a",
                "muid": "feb2e914-b374-4b00-9473-0cf6b59cbc8fae1ab1",
                "sid": "93d1a515-93c6-433e-a5eb-55c60f41adb4651050",
                "referrer": "https://estatesales.org",
                "time_on_page": "165929",
                "card[number]": cardInfo.cardNumber,
                "card[cvc]": cardInfo.cvc,
                "card[exp_month]": cardInfo.expMonth,
                "card[exp_year]": cardInfo.expYear,
                "card[address_zip]": cardInfo.zipCode,
                "payment_user_agent": "stripe.js/998c3861d3; stripe-js-v3/998c3861d3; card-element",
                "pasted_fields": "number,zip",
                "key": "pk_live_dpumrPfEyOd89VgTTGpl1DFH"
            })
        });

        const tokenData = await tokenResponse.json();
        console.log(`[${new Date().toLocaleString()}] Stripe token响应:`, {
            status: tokenResponse.status,
            statusText: tokenResponse.statusText,
            tokenId: tokenData.id ? "已生成" : "未生成"
        });

        if (!tokenData.id) {
            throw new Error("Failed to create Stripe token");
        }

        // 第二步：绑定支付方式
        console.log(`[${new Date().toLocaleString()}] 正在绑定支付方式...`);
        const bindResponse = await fetch("https://estatesales.org/api/v3/user/payment-method/stripe", {
            method: "POST",
            headers: {
                "accept": "application/json, text/plain, */*",
                "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
                "cookie": "eso=UaKoF544ujVhefz65eZrOVPVarvcWcp3; _gcl_au=1.1.1163855875.1744386172; _ga=GA1.1.1410305055.1744386182; ConsentState=accepted; ndp_session_id=315d4870-c96a-4fcf-905b-80c6108ef7c4; _li_dcdm_c=.estatesales.org; _lc2_fpi=69f3e8e9573a--01jrjrahna147w5aymvhz0jszv; _lc2_fpi_js=69f3e8e9573a--01jrjrahna147w5aymvhz0jszv; tracedata=ip%3D47.149.50.190%26uag%3DMozilla%2F5.0%20(Macintosh%3B%20Intel%20Mac%20OS%20X%2010_15_7)%20AppleWebKit%2F537.36%20(KHTML%2C%20like%20Gecko)%20Chrome%2F135.0.0.0%20Safari%2F537.36%26loc%3DUS%26colo%3DLAX; _li_ss=CoYBCgYI-QEQwRoKBQgKEMEaCgYIpAEQwRoKBgjdARDBGgoFCAkQwRoKBgiBARDBGgoFCAwQyxoKBgj1ARDBGgoGCKIBEMEaCgkI_____wcQyxoKBQgLEMEaCgYIiQEQwRoKBgilARDBGgoGCIACEMMaCgYI4QEQwRoKBgjSARDBGgoFCH4QwRo; _ga_9K5SM8KWDD=GS1.1.1744386182.1.1.1744386658.22.0.0; __stripe_mid=feb2e914-b374-4b00-9473-0cf6b59cbc8fae1ab1; __stripe_sid=93d1a515-93c6-433e-a5eb-55c60f41adb4651050; key=value"
            },
            body: new URLSearchParams({
                "token": tokenData.id
            })
        });

        const bindResult = await bindResponse.json();
        console.log(`[${new Date().toLocaleString()}] 绑卡响应:`, {
            status: bindResponse.status,
            statusText: bindResponse.statusText,
            result: bindResult
        });

        if (bindResponse.ok) {
            console.log(`[${new Date().toLocaleString()}] 绑卡成功！`);
            
            // 第三步：删除绑定的卡片
            console.log(`[${new Date().toLocaleString()}] 正在删除绑定的卡片...`);
            const deleteResponse = await fetch("https://estatesales.org/api/v3/user/payment-method/stripe", {
                method: "DELETE",
                headers: {
                    "accept": "application/json, text/plain, */*",
                    "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
                    "cookie": "eso=UaKoF544ujVhefz65eZrOVPVarvcWcp3; _gcl_au=1.1.1163855875.1744386172; _ga=GA1.1.1410305055.1744386182; ConsentState=accepted; ndp_session_id=315d4870-c96a-4fcf-905b-80c6108ef7c4; _li_dcdm_c=.estatesales.org; _lc2_fpi=69f3e8e9573a--01jrjrahna147w5aymvhz0jszv; _lc2_fpi_js=69f3e8e9573a--01jrjrahna147w5aymvhz0jszv; tracedata=ip%3D47.149.50.190%26uag%3DMozilla%2F5.0%20(Macintosh%3B%20Intel%20Mac%20OS%20X%2010_15_7)%20AppleWebKit%2F537.36%20(KHTML%2C%20like%20Gecko)%20Chrome%2F135.0.0.0%20Safari%2F537.36%26loc%3DUS%26colo%3DLAX; _li_ss=CoYBCgYI-QEQwRoKBQgKEMEaCgYIpAEQwRoKBgjdARDBGgoFCAkQwRoKBgiBARDBGgoFCAwQyxoKBgj1ARDBGgoGCKIBEMEaCgkI_____wcQyxoKBQgLEMEaCgYIiQEQwRoKBgilARDBGgoGCIACEMMaCgYI4QEQwRoKBgjSARDBGgoFCH4QwRo; __stripe_mid=feb2e914-b374-4b00-9473-0cf6b59cbc8fae1ab1; __stripe_sid=93d1a515-93c6-433e-a5eb-55c60f41adb4651050; key=value"
                }
            });

            const deleteResult = await deleteResponse.json();
            console.log(`[${new Date().toLocaleString()}] 删除卡片响应:`, {
                status: deleteResponse.status,
                statusText: deleteResponse.statusText,
                result: deleteResult
            });

            if (deleteResponse.ok) {
                console.log(`[${new Date().toLocaleString()}] 删除卡片成功！`);
            } else {
                console.error(`[${new Date().toLocaleString()}] 删除卡片失败！`);
            }

            return {
                bindResult: {
                    ...bindResult,
                    success: true
                },
                deleteResult
            };
        } else {
            console.error(`[${new Date().toLocaleString()}] 绑卡失败！`);
            return {
                bindResult: {
                    ...bindResult,
                    success: false
                },
                deleteResult: null
            };
        }

    } catch (error) {
        console.error(`[${new Date().toLocaleString()}] 操作过程中发生错误:`, error);
        throw error;
    }
}

// 导出函数
module.exports = {
    autoBindCard
};